package handlers

import (
	"go-mysql-rec/models"
	"net/http"
	"strconv"

	"github.com/labstack/echo"
)

// GetRecords get record list
func (h *Handler) GetRecords() echo.HandlerFunc {
	return func(c echo.Context) error {
		return c.JSON(http.StatusOK, models.GetRecords(h.DB))
	}
}

//PutRecord add new record
func (h *Handler) PutRecord() echo.HandlerFunc {
	return func(c echo.Context) error {
		var record models.Record

		c.Bind(&record)

		id, err := models.PutRecord(h.DB, record.Name, record.Content)

		if err == nil {
			return c.JSON(http.StatusCreated, H{
				"created": id,
			})
		}
		return err
	}
}

//DeleteRecord delete record
func (h *Handler) DeleteRecord() echo.HandlerFunc {
	return func(c echo.Context) error {
		var record models.Record
		id, _ := strconv.ParseInt(c.Param("id"), 10, 64)

		c.Bind(&record)

		id, err := models.DeleteRecord(h.DB, id)

		if err != nil {
			panic(err)
		}
		return c.JSON(http.StatusOK, H{
			"deleted": id,
		})
	}
}
